package com.example.spring_boot_demo.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description:  记录接口访问的总时长
 * <P> Date: 2024/12/18:16:34
 */

@SuppressWarnings({"unchecked", ""})

public class MyInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MyInterceptor.class);
    long startTime;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        startTime = System.currentTimeMillis();
        log.info("线程：{} ,controller 之前 执行,执行开始时间；{}",Thread.currentThread().getName(),startTime);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        log.info("线程：{} ,controller 之前 执行,postHandle",Thread.currentThread().getName());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        log.info("controller 执行完毕");
        long endTime = System.currentTimeMillis();
        log.info("线程：{} ,开始时间：{},接口总耗时；{}",Thread.currentThread().getName(),startTime,endTime - startTime);
    }


}
